package com.cloud.user.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.security.Signature;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author tangyuan2meicloud.com
 * @DATE 2021/7/7 14:01
 * @Desc
 * @Remarks
 */

/**
 * JWT JSON web Token 工具类
 *  json字符串的提供加密和解密方法
 *
 *
 *  JWT ：
 *  HEADER:ALGORITHM
 *      {
 *   "alg": "HS256",
 *   "typ": "JWT"
 * }
 *
 * PAYLOAD:DATA
 * {
 *   "sub": "1234567890",
 *   "name": "John Doe",
 *   "iat": 1516239022
 * }
 *
 * VERIFY SIGNATURE
 * HMACSHA256(
 *   base64UrlEncode(header) + "." +
 *   base64UrlEncode(payload),
 *  your-256-bit-secret
 * )
 *
 */
@Slf4j
public class TokenUtils {

    public static final String SECRET = "tangyuan";

    public static Key getKeyInstance() {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] bytes = DatatypeConverter.parseBase64Binary(SECRET);
        Key key = new SecretKeySpec(bytes, signatureAlgorithm.getJcaName());
        return key;
    }

    public static String generatorToken(Map<String, Object> payloadMap) {
        ObjectMapper objectMapper = new ObjectMapper();

        String token = null;
        try {
            token = Jwts.builder().setPayload(objectMapper.writeValueAsString(payloadMap)).
                    signWith(SignatureAlgorithm.HS256, getKeyInstance()).
                    compact();
        } catch (Exception e) {
            log.info(e.getMessage());
        } finally {
        }
        return token;
    }

    public static Claims parseToken(String token) {
        Claims body = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token).getBody();
        return body;
    }
}
